package com.crazymakercircle.visiable;

import lombok.extern.slf4j.Slf4j;

@Slf4j
class ReorderDemo {
    int value = 10;
    boolean flag = false;
    int doubleValue = 0;

    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        int i = 0;
        for (; ; ) {
            i++;
            ReorderDemo reorderDemo = new ReorderDemo();
            Thread one = new Thread(reorderDemo::write);
            Thread two = new Thread(reorderDemo::changeValue);
            one.start();
            two.start();
            one.join();
            two.join();

            if (reorderDemo.doubleValue == 20) {
                String result = "第" + i + "次操作发生了指令重排";
                log.info("ret:{},cost:{} ms", result, System.currentTimeMillis() - start);
            }
        }
    }

    // 如果1和2发生了指令重排得话那么doubleValue的值就是20
    public void write() {
        value = 100;      //①
        flag = true;    //②
    }

    public void changeValue() {
        if (flag) {  //③
            doubleValue = value + value;//④
        }
    }
}
